﻿'''
54 螺旋矩阵
给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
示例 1：
输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出：[1,2,3,6,9,8,7,4,5]
示例 2：
输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出：[1,2,3,4,8,12,11,10,9,5,6,7]
提示：
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
'''
class Solution:
    def spiralOrder(self,matrix:list[list[int]])->list[int]:
        if not matrix or not matrix[0]:
            return []
        row, col = len(matrix),len(matrix[0])
        left,right = 0, col-1
        top,bottom = 0, row-1
        result = []
        while left <= right and top <= bottom:
            #每次遍历都需判断是否遍历完，即left<=right and top<= bottom,无变化不需要，都变化都需要
            #遍历上边
            for i in range(left,right+1):
                result.append(matrix[top][i])
            top += 1
            #遍历右边
            for i in range(top,bottom+1):
                result.append(matrix[i][right])
            right -= 1
            #遍历下边
            if top <= bottom:
                for i in range(right,left-1,-1):
                    result.append(matrix[bottom][i])
                bottom -= 1
            #遍历左边
            if left <= right:
                for i in range(bottom,top-1,-1):
                    result.append(matrix[i][left])
                left += 1
        return result
#示例
if __name__ == '__main__':
    matrix = [[1,2,3],[4,5,6],[7,8,9]]
    matrix1 = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
    matrix2 = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
    print(Solution().spiralOrder(matrix))
    print(Solution().spiralOrder(matrix1))
    print(Solution().spiralOrder(matrix2))


